package com.aischool.api;

import java.util.List;

import com.aischool.common.model.SysMenu;
import com.aischool.routes.RouteMapping;
import com.aischool.service.SysAppService;
import com.aischool.service.SysMenuService;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

@RouteMapping(url = "/api/menu")
public class MenuController extends Controller {

	@Inject
	SysAppService sysAppService;
	@Inject
	SysMenuService sysMenuService;
	
	public void getAll() {
		// 结果类
		JsonResult jr = new JsonResult();
		int app_id = getInt("so_app_id", 0);
		int menu_state = getInt("state");
		
		if (app_id <= 0) {
			List<Record> listApp = sysAppService.getSysAppAll();
			if (listApp!=null&&listApp.size()>0) {
				app_id = listApp.get(0).getInt("app_id");
				jr.setDicKV("listapp", listApp);
			}
		}
		
		if (app_id > 0) {
			Object obj = sysMenuService.getAppMenu(app_id, menu_state);
			jr.setDicKV("listmenu", obj);
		}
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void getMenu() {
		// 结果类
		JsonResult jr = new JsonResult();
		int app_id = getParaToInt("so_app_id", 0);
		int menu_id = getParaToInt("id",0);
		
		List<Record> listApp = sysAppService.getSysAppAll();
		if (listApp!=null&&listApp.size()>0) {
			jr.setDicKV("listapp", listApp);
		}
		
		if (menu_id>0) {
			Record rd = sysMenuService.getMenu(menu_id);
			if (rd != null) {
				app_id = rd.getInt("app_id");
				jr.setDicKV("menudata", rd);
			}
		}
		
		if (app_id>0) {
			Object obj = sysMenuService.getAppMenu(app_id, 1);
			jr.setDicKV("listmenu", obj);
		}
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void save() {
		// 结果类
		JsonResult jr = new JsonResult();
		// 表单转换类
		int menu_id = getParaToInt("menu_id", 0);
		
		SysMenu info = getModel(SysMenu.class, "", true);
		info.setMenuUrl(getPara("menu_url", ""));
		info.setIconCode(getPara("icon_code", ""));
		
		info.removeNullValueAttrs();
		
		boolean bf = false;
		if (menu_id>0) {
			bf = info.update();
		}else {
			bf = info.save();
		}
		
		if (bf) {
			sysMenuService.removeCache();
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			jr.setEnum(JsonCodeEnum.Faild);
		}
		
		renderJson(jr.Dic);
	}
	
	public void del() {
		// 结果类
		JsonResult jr = new JsonResult();
		// 表单转换类
		int menu_id = getParaToInt("id", 0);
		
		
		boolean bf = sysMenuService.updateMenuState(menu_id, -1);
		
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			jr.setEnum(JsonCodeEnum.Faild);
		}
		
		renderJson(jr.Dic);
	}
}
